<template>
  <div class="wps">
    <div class="header" :class="[systemSettingStore.$state.deskAppRangeType]">
      <ul class="menu-bar">
        <li class="logo" :class="{ checked: currentId === '' }" @click.stop="handleChangeSelect(null)">
          <img src="@/assets/images/app/wps.png" alt="wps" />
          WPS Office
        </li>
        <li
          v-for="(item, index) in menuList"
          :key="item.id"
          :class="{ checked: currentId === item.id }"
          @click.stop="handleChangeSelect(item)"
          @dblclick.stop
        >
          <img :src="item.src" alt="logo" />
          <p>{{ item.name }}</p>
          <span @click.stop="handleClose(item, index)">
            <i class="iconfont wos-close-wechat fs18" />
          </span>
        </li>
        <li class="add" @click.stop="handleCreateOffice" @dblclick.stop>
          <i class="iconfont wos-add" />
        </li>
      </ul>
      <system-child-btn theme="light" />
    </div>
    <keep-alive>
      <component
        class="content"
        :is="currentComponent"
        :data="currentData"
        :history-list="historyList"
        @mousedown.stop
        @dblclick.stop
        @history="handleChangeSelect"
      />
    </keep-alive>
  </div>
</template>

<script setup lang="ts">
import SystemChildBtn from '@/base/systemWindow/systemChildBtn.vue'
import WpsIndex from '@/components/systemWindow/wps/wpsIndex.vue'
import WpsPdf from '@/components/systemWindow/wps/wpsPdf.vue'
import WpsWord from '@/components/systemWindow/wps/wpsWord.vue'
import WpsExcel from '@/components/systemWindow/wps/wpsExcel.vue'
import { inject, markRaw, onBeforeMount, reactive, ref } from 'vue'
import { getFileType, getFileTypeToOffice, getImageUrl, randomWord, readFile, selectFile } from '@/utils/utils'
import { useRunningTasksStore } from '@/stores/taskBar/runningTasks'
import { addFileDBStore, clearFileDBStore, deleteFileDBStore, getFileDBStore } from '@/dbStore/fileStore'
import { useSystemSettingStore } from '@/stores/desk/systemSetting'
import { WALLPAPER } from '@/hooks/systemWindowHooks'
import type { Component, Raw } from 'vue'

type IWpsListKey = 'wpsIndex' | 'pdf' | 'docx' | 'xlsx'
type ILocalFilesKey = 'pdf' | 'docx' | 'xlsx'

export interface IHistoryList {
  id: string
  name: string
  size: number
  date: number
  path: string
  src: string
  file: string
  isLocal: boolean
}

const runningTaskStore = useRunningTasksStore()
const systemSettingStore = useSystemSettingStore()

const appId = inject<string>('appId') || ''
const taskId = inject<string>('taskId') || ''
const componentData = inject<{
  [key: string]: unknown
}>('componentData')

// 本地文件
const localFiles: { [key in ILocalFilesKey]: string } = {
  pdf: new URL('../../../assets/document/resume.pdf', import.meta.url).href,
  docx: new URL('../../../assets/document/vue.docx', import.meta.url).href,
  xlsx: new URL('../../../assets/document/test.xlsx', import.meta.url).href
}
// 当前窗口
const currentComponent = ref<Component>(markRaw(WpsIndex))
// 当前选中的数据
const currentId = ref<string>((componentData?.currentId as string) || '')
// 当前文档数据
const currentData = ref<string>('')
// 顶部tab
const menuList = ref<IHistoryList[]>((componentData?.menuList as IHistoryList[]) || [])
// 历史浏览记录列表
const historyList = reactive<IHistoryList[]>([
  {
    id: 'resume.pdf',
    name: '个人简历.pdf',
    size: 298 * 1024,
    date: new Date().getTime(),
    path: 'C:\\Users\\asus\\Desktop',
    src: getImageUrl('wps/pdf.png'),
    file: 'pdf',
    isLocal: true
  },
  {
    id: 'vue2.0.docx',
    name: 'vue2.0.docx',
    size: 1023 * 1024,
    date: new Date().getTime(),
    path: 'C:\\Users\\asus\\Desktop',
    src: getImageUrl('wps/word.png'),
    file: 'docx',
    isLocal: true
  },
  {
    id: 'test.xlsx',
    name: '年度考情报表.xlsx',
    size: 336 * 1024,
    date: new Date().getTime(),
    path: 'C:\\Users\\asus\\Desktop',
    src: getImageUrl('wps/excel.png'),
    file: 'xlsx',
    isLocal: true
  }
])
// 组件列表
const wpsComponentList = reactive<{ [key in IWpsListKey]: Raw<Component> }>({
  wpsIndex: markRaw(WpsIndex),
  pdf: markRaw(WpsPdf),
  docx: markRaw(WpsWord),
  xlsx: markRaw(WpsExcel)
})

// 创建office文档
const handleCreateOffice = async () => {
  const files = await selectFile({ accept: '.docx,.pdf,.xlsx' })
  const file = files[0]
  const base64 = await readFile(file, 'toBase64')
  const type = getFileType(file.name)
  const office = getFileTypeToOffice(file.name)
  const fileId = randomWord(20, 'file-base64-')
  await addFileDBStore(fileId, base64)
  const data = {
    id: fileId,
    name: file.name,
    size: file.size,
    date: new Date().getTime(),
    path: file.webkitRelativePath,
    src: getImageUrl(`wps/${office}.png`),
    file: type,
    isLocal: false
  }
  await handleChangeSelect(data)
}

// 新增tab列表
const handleAddMenu = (data: IHistoryList): boolean => {
  const off = menuList.value.some((item) => item.id === data.id)
  if (!off) menuList.value.push(data)
  return off
}

// 关闭tab
const handleClose = async (data: IHistoryList, index: number) => {
  if (currentId.value === data.id) {
    const data = menuList.value[index + 1]
      ? menuList.value[index + 1]
      : menuList.value[index - 1]
        ? menuList.value[index - 1]
        : null
    await handleChangeSelect(data)
  }
  if (!data.isLocal) await deleteFileDBStore(data.id)
  menuList.value = menuList.value.filter((item) => item.id !== data.id)
  runningTaskStore.setTaskPatch(appId, taskId, {
    componentData: {
      currentId: menuList.value.length ? currentId.value : '',
      menuList: menuList.value
    }
  })
}

// 历史记录点击选择事件
const handleChangeSelect = async (data: IHistoryList | null) => {
  if (!data) {
    currentId.value = ''
    currentData.value = ''
    currentComponent.value = wpsComponentList['wpsIndex']
    runningTaskStore.setTaskPatch(appId, taskId, {
      componentData: {
        currentId: ''
      }
    })
    return
  }
  const type = getFileType(data.name)
  if (data.isLocal) {
    currentData.value = localFiles[data.file as ILocalFilesKey]
  } else {
    try {
      const { base64 } = await getFileDBStore(data.id)
      currentData.value = base64
    } catch {
      const index = menuList.value.findIndex((item) => item.id === data.id)
      await handleClose(data, index)
    }
  }
  handleAddMenu(data)
  currentId.value = data.id
  currentComponent.value = wpsComponentList[type as ILocalFilesKey]
  runningTaskStore.setTaskPatch(appId, taskId, {
    componentData: { currentId: data.id, menuList: menuList.value }
  })
}

const init = async () => {
  const menuList = componentData?.menuList as IHistoryList[]
  if (componentData?.currentId) {
    const list = menuList?.length ? menuList : historyList
    const find = list.find((item) => item.id === componentData?.currentId)
    find && (await handleChangeSelect(find))
  }
  if (!menuList?.length) {
    const wallpaper = await getFileDBStore(WALLPAPER)
    await clearFileDBStore()
    if (wallpaper?.base64) await addFileDBStore(WALLPAPER, wallpaper.base64)
  }
}

onBeforeMount(() => {
  init()
})
</script>

<style scoped lang="scss">
.wps {
  width: 100%;
  height: 100%;
  background-color: rgb(230, 234, 236);

  .header {
    height: 42px;
    position: relative;
    display: flex;
    align-items: center;

    &.ios {
      padding-left: 80px;
    }

    .menu-bar {
      width: calc(100% - 200px);
      display: flex;
      align-items: center;
      overflow-x: auto;

      li {
        position: relative;
        margin-left: 5px;
        width: 245px;
        height: 32px;
        display: flex;
        padding-left: 10px;
        align-items: center;
        justify-content: flex-start;
        border-radius: 8px;
        box-sizing: border-box;
        background-color: rgb(217, 222, 224);
        border: 1px solid transparent;

        &.logo {
          width: 116px;
          min-width: 116px;
        }

        &.add {
          width: auto;
          border-radius: 0;
          background-color: transparent !important;
        }

        &.checked {
          background-color: #fff;
          border-color: rgb(208, 213, 216);
        }

        &:hover {
          background-color: #fff;

          > span {
            display: inline-flex;
          }
        }

        img {
          width: 16px;
          height: 16px;
          object-fit: contain;
          margin-right: 5px;
        }

        p {
          width: calc(100% - 60px);
          white-space: nowrap;
          overflow-y: hidden;
          text-overflow: ellipsis;
        }

        > span {
          position: absolute;
          right: 10px;
          top: 50%;
          transform: translateY(-50%);
          display: none;
          justify-content: center;
          align-items: center;
          width: 18px;
          height: 18px;
          border-radius: 2px;

          &:hover {
            background-color: rgb(232, 234, 235);
          }
        }
      }
    }
  }

  .content {
    box-sizing: border-box;
    padding-top: 6px;
    width: 100%;
    height: calc(100% - 42px);
  }
}
</style>
